import os

from flask import Flask, request, g
from volcenginesdkarkruntime import Ark, AsyncArk

from controller.article import article_blueprint
from controller.category import category_blueprint
from controller.app import app_blueprint
from controller.file import file_blueprint
from controller.test import test_blueprint
from config import Config, WHITE_LIST,AiConfig,DOUBAO_API_KEY
from controller.graph import graph_blueprint
from controller.question import question_blueprint
from controller.scoring_result import scoring_blueprint
from controller.user import user_blueprint
from controller.userAnswer import userAnswer_bluePrint
from controller.AI import ai_blueprint
from models import db,User
from utils import JWT, ThreadLocal
from common import ApiResponse,BaseResponse
from common.ErrorCode import ErrorCode
app = Flask(__name__)


class ArkAsyncExtension:
    def __init__(self, api_key=None):
        self.api_key = api_key

    def init_app(self, app):
        self.api_key = self.api_key or DOUBAO_API_KEY or os.environ.get("ARK_API_KEY")
        app.extensions["async_ark"] = AsyncArk(api_key=self.api_key)


# 初始化扩展
ark_ext = ArkAsyncExtension(api_key=os.environ.get("ARK_API_KEY"))
ark_ext.init_app(app)
app.config.from_object(Config)
app.config['JSON_SORT_KEYS'] = False
db.init_app(app)
app.register_blueprint(article_blueprint, url_prefix='/article')
app.register_blueprint(category_blueprint, url_prefix='/category')
app.register_blueprint(user_blueprint, url_prefix='/user')
app.register_blueprint(graph_blueprint, url_prefix='/graph')
app.register_blueprint(file_blueprint, url_prefix='/file')
app.register_blueprint(app_blueprint,url_prefix='/app')
app.register_blueprint(question_blueprint, url_prefix='/question')
app.register_blueprint(scoring_blueprint,url_prefix='/scoring')
app.register_blueprint(userAnswer_bluePrint,url_prefix='/userAnswer')
app.register_blueprint(ai_blueprint,url_prefix='/ai')
app.register_blueprint(test_blueprint,url_prefix='/test')
app.config['DEBUG'] = False
# with app.app_context():
#     users = User.query_active().filter(User.id <=10).all()
#     print(users)


@app.before_request
def preHandle():
    print("preHandling")
    try:
        if request.path in WHITE_LIST:
            return
        token = request.headers.get('Authorization')
        if not token:
            return ApiResponse.ApiResponse.error("缺少认证token")
        try:
            user_map = JWT.JWTUtil.parse_token(token)
            ThreadLocal.ThreadLocalUtil.set(user_map)
            g.user_map = user_map  # 使用 g 对象存储用户信息
        except Exception as e:
            print("token已过期")
            error_response = BaseResponse.BaseResponse.from_error_code(ErrorCode.NOT_LOGIN_ERROR)
            return ApiResponse.ApiResponse.error_from_baseResponse(error_response, data="无效的token")
    except Exception as e:
        error_response = BaseResponse.BaseResponse.from_error_code(ErrorCode.NOT_LOGIN_ERROR)
        return ApiResponse.ApiResponse.error_from_baseResponse(error_response,data="无效的token")


@app.after_request
def after_request(response):
    ThreadLocal.ThreadLocalUtil.remove()
    return response


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host="0.0.0.0", port=8080)
